package actions;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

import utils.Constants;
import utils.ImageCreator;
import client.ClientSocketConnection;
import client_gui.BlockListDialog;
import client_gui.ClientWindow;
import client_gui.FindUserDialog;
import client_tree.User;


/**
 * Klasa koja predstavlja akciju Add dugmeta u FindUser dialogu.
 * Ova klasa je izdvojena od ostalih Action klasa (nasledjuje JButton), jer
 * se objekat ove klase dodaje direktno u JPanel, a ne u JToolBar ili JMenu.
 * 
 * @author UrosKrkic & Radivoje Popovic
 */
public class AddUserAction extends JButton implements ActionListener, Constants {

	
	/**
	 * Vlasnik akcije.
	 */
	private ClientWindow owner;
	
	
	/**
	 * Glavni prozor aplikacije.
	 */
	private FindUserDialog parent = null;
	
	private BlockListDialog parent2 = null;
	

	/**
	 * Konstruktor.
	 * @param owner - vlasnik akcije
	 * @param label - naziv dugmeta
	 * @author UrosKrkic & Radivoje Popovic
	 */
	public AddUserAction(ClientWindow owner, JDialog parent) {
		super();
		this.setToolTipText("Add user");
		
		this.owner = owner;
		
		if (parent instanceof FindUserDialog)
			this.parent = (FindUserDialog)parent;
		else {
			this.parent2 = (BlockListDialog)parent;
		}
		
		this.setIcon(ImageCreator.createImageIcon(AddUserAction.class, "images/add.png"));
		
		this.addActionListener(this);
	}
	

	
	/**
	 * Metod koji setuje vlasnika ove akcije. Za razliku od klasa akcija, koje
	 * prosiruju RLMAbstarctAction, u LogginAction klasi moguce je pristupiti vlasniku
	 * akcije direktno. Metod je uveden samo zbog ocuvanja doslednosti u interfejsu za
	 * rukovanje akcijama
	 * @param owner - vlasnik aplikacije
	 * @author UrosKrkic & Radivoje Popovic
	 */
	public void setActionOwner(ClientWindow owner) {
		this.owner = owner;
	}
	
	
	
	/**
	 * Metod koji vraca referencu na vlasnika ove akcije. Za razliku od klasa akcija, koje
	 * prosiruju RLMAbstarctAction, u LogginAction klasi moguce je pristupiti vlasniku
	 * akcije direktno. Metod je uvede samo zbog ocuvanja doslednosti u interfejsu za
	 * rukovanje akcijama
	 * @author UrosKrkic & Radivoje Popovic
	 */
	public ClientWindow getActionOwner() {
		return this.owner;
	}

	
	@SuppressWarnings("unchecked")
	public void actionPerformed(ActionEvent e) {

		Vector row = null;
		
		if (parent != null) {
			row = parent.getSelectedRow();
		}
		else {
			ClientSocketConnection connection = owner.getApplicaton().retrieveSocketConnection();
			
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("FIND ");
			buffer.append(owner.getApplicaton().getClientUser().getUsername());
			buffer.append(" ");
			buffer.append(parent2.getSelectedValueNotInCL());
			buffer.append(" ");
			buffer.append("username");
			buffer.append(" ");
			buffer.append("true");
			
			String completedFindInfo = buffer.toString();
			
			connection.setMessage(ADD_CMD, completedFindInfo);
		
			String response;
			
			response = connection.buffers[ADD_CMD].read();
			
				
			if (response.startsWith("100")) {
				StringTokenizer tokens = new StringTokenizer(response);
				tokens.nextToken();
				tokens.nextToken();
				
				int rowCount = Integer.parseInt(tokens.nextToken());
				
				if (rowCount == 0) {
					if (parent != null)
						JOptionPane.showMessageDialog(parent, "No results found.", "Find Info", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				
				response = connection.buffers[ADD_CMD].read();
				StringTokenizer responseTokens = new StringTokenizer(response);
				
				row = new Vector<String>();
				
				for (int i = 0; i < 9; i++) {
					row.add(i, (String)responseTokens.nextToken());
				}
			}
		}
		
		if (row != null) {
			
			String username = row.get(0).toString();
			String nickname = row.get(1).toString();
			String email = row.get(2).toString();
			String ip_address = row.get(3).toString();
			String localAddress = row.get(4).toString();
			String port = row.get(5).toString();
			String status = row.get(6).toString();
			String regDate = row.get(7).toString();
			String avatar = row.get(8).toString();
			
			if (parent != null)
				parent.removeSelectedRow();
			

			ClientSocketConnection connection = owner.getApplicaton().retrieveSocketConnection();
			StringBuffer buffer = new StringBuffer();
			
			buffer.append("ADD ");
			buffer.append(owner.getApplicaton().getClientUser().getUsername());
			buffer.append(" ");
			buffer.append(username);
			
			String completedAddUserInfo = buffer.toString();
			
			connection.setMessage(ADD_CMD, completedAddUserInfo);
			
			String response;
			
			response = connection.buffers[ADD_CMD].read();
			
			if ( response.startsWith("100") ) {
				User user = new User(username, nickname, email, ip_address, localAddress, Integer.parseInt(port), status, regDate, avatar);

				owner.getApplicaton().getClientModel().addUser(user);				
			}
			else {
				String warningMessage = "User \" " + username + "\" is not member of this beautiful messenger comunity!";
				JOptionPane.showMessageDialog(getActionOwner(), warningMessage, "Adding User", JOptionPane.WARNING_MESSAGE);
			}
			
		}
	}
		
}
